import axios from "axios";
import router from "@/routes/index";
import { API_BASE_URL } from "@/utils/config/index";

const set = new Set();
const pendingRequests = new Map<string, AbortController>();

const generateUniqueKey = (config: any, hash: any) => {
    const { method, url, params, data } = config;
    return [method, url, JSON.stringify(params), JSON.stringify(data), hash].join('&');
}

const http = axios.create({
    baseURL: API_BASE_URL,
    headers: {
        AUTHORIZATION: window.localStorage.getItem("token"),
    },
});

http.interceptors.request.use(
    (config: any) => {
        const hash = location.hash;
        const reqKey = generateUniqueKey(config, hash);

        // 如果请求重复，直接拒绝本次请求
        if (set.has(reqKey)) {
            return Promise.reject('Duplicate request');
        } else {
            // 保存请求的唯一标识符
            config.pendKey = reqKey;
            set.add(reqKey); // 将请求的唯一标识符加入 set
        }
        // 为每个请求创建 AbortController
        const controller = new AbortController();
        pendingRequests.set(reqKey, controller);
        config.signal = controller.signal;

        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

http.interceptors.response.use(
    (res: any) => {
        const reqKey = res.config.pendKey;
        set.delete(res.config.pendKey);
        pendingRequests.delete(reqKey);

        if (res.data.code == -2) {
            window.localStorage.clear();
            window.location.href = `/login?redirect=${router.currentRoute.value.fullPath}`;
        } else return res.data;
    },
    (error) => {
        if (error.config && error.config.pendKey) {
            const reqKey = error.config.pendKey;
            set.delete(error.config.pendKey);
            pendingRequests.delete(reqKey);
            if (JSON.parse(error.request.response)?.code == -2) {
                window.localStorage.clear();
                window.location.href = `/login?redirect=${router.currentRoute.value.fullPath}`;
            }
        }
        if (error !== "Duplicate request") return Promise.reject(error);
    }
);

export function cancelAllPendingRequests(reason = '路由切换取消请求') {
    pendingRequests.forEach((controller, key) => {
        controller.abort(reason);
        pendingRequests.delete(key);
        set.delete(key);
    });
}
export default http;
